#include <stdlib.h>
#include <stdio.h>

#include "webrtc/modules/audio_processing/aec/include/echo_cancellation.h"

#define FRAMEINT16 160
#define FRAMEBYTE (160*2)

int main(int argc, char *argv[])
{
    FILE *fidnear = fopen(argv[1], "rb");
	fseek(fidnear, 0, SEEK_END); int d2 = ftell(fidnear);
    fseek(fidnear, 0, SEEK_SET); int d1 = ftell(fidnear);
    int nframes = (d2-d1)/FRAMEBYTE;
    printf("total frames = %d\n", nframes);

    FILE *fidfar = fopen(argv[2], "rb");
    FILE *fidaec = fopen(argv[3], "wb");
    short micbuf[FRAMEINT16] = {0};
    short refbuf[FRAMEINT16] = {0};
    short aecbuf[FRAMEINT16] = {0};
    float near[FRAMEINT16] = {0.0f};
    float far[FRAMEINT16] = {0.0f};
    float aec[FRAMEINT16] = {0.0f};
    float *mic_ptr[3] = {near, NULL, NULL}; // 三个子带
    float *aec_ptr[3] = {aec, NULL, NULL};
    

    void *aecInst = WebRtcAec_Create();
    WebRtcAec_Init(aecInst, 16000, 16000);
    AecConfig config;
    config.nlpMode = 0;/*0,1,2*/
    config.delay_logging = 0;
    config.metricsMode = 0;
    config.skewMode = 0;
    WebRtcAec_set_config(aecInst, config);

    for (int n=0; n<nframes; n++) {
        fread(micbuf, sizeof(short), FRAMEINT16, fidnear);
        fread(refbuf, sizeof(short), FRAMEINT16, fidfar);
        for (int i=0; i<FRAMEINT16; i++) {
            near[i] = micbuf[i]*1.0f;
            far[i] = refbuf[i]*1.0f;
        }
        WebRtcAec_BufferFarend(aecInst, far, FRAMEINT16);
        WebRtcAec_Process(aecInst, mic_ptr, 1, aec_ptr, FRAMEINT16, 30/*ms*/, 0);
        for (int i=0; i<FRAMEINT16; i++) {
            aecbuf[i] = (short)aec[i];
        }
        fwrite(aecbuf, sizeof(short), FRAMEINT16, fidaec);
    }

    WebRtcAec_Free(aecInst);
    fclose(fidnear); fclose(fidfar); fclose(fidaec);
    return 0;
}